#include "NewProjectDialog.h"
#include "ui_NewProjectDialog.h"
#include <QFileDialog>
#include <QDateTime>
#include <QFile>
#include <QMessageBox>
NewProjectDialog::NewProjectDialog(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::NewProjectDialog)
{
    ui->setupUi(this);
    setWindowTitle("新建工程");
    QString path = QDir::currentPath()+QString("/project");
    ui->lineEdit_2->setText(path);
    ui->lineEdit_3->setText("工程文件");

    for(int i = 1 ; i <100 ;i++)
    {
        QString strName = "project"+QString::number(i);
        QString strProjectName = path+"/"+strName+".pxm";
        if(!ExistFile(strProjectName))
        {
            ui->lineEdit->setText(strName);
            break;
        }
    }
}

NewProjectDialog::~NewProjectDialog()
{
    delete ui;
}

QString NewProjectDialog::GetInputProjectName()
{
    return ui->lineEdit->text();
}

QString NewProjectDialog::GetInputPath()
{
    return ui->lineEdit_2->text();
}

stProject NewProjectDialog::GetProjectInfo()
{
    stProject project;
    project.createTime =  QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss").toStdString();
    project.name = ui->lineEdit->text().toStdString();
    project.desc = ui->lineEdit_3->text().toStdString();
    project.path = ui->lineEdit_2->text().toStdString();

    return project;
}

bool NewProjectDialog::ExistFile(QString fileName)
{
    QFile file(fileName);
    if(file.exists())
    {
        ui->label_FileExist->setStyleSheet("color: rgb(255, 0, 0);");
        ui->label_FileExist->setText("文件已存在");
        return true;
    }else
    {
         ui->label_FileExist->setText("");
         return false;
    }
}

void NewProjectDialog::on_pushButton_2_clicked()
{
     QString filePath = ui->lineEdit_2->text() +"/" + ui->lineEdit->text() +".pxm";
    if(ExistFile(filePath))
    {
        QMessageBox::information(nullptr,"新建工程","文件已经存在，请重新输入");
    }else
    QDialog::accept();
}

void NewProjectDialog::on_pushButton_clicked()
{
    QString folder = QFileDialog::getExistingDirectory(
                nullptr, QObject::tr("Open Folder"),QDir::homePath());
    if(!folder.isNull())
    {
        ui->lineEdit_2->setText(folder);
    }
}

void NewProjectDialog::on_pushButton_3_clicked()
{
      QDialog::close();
}

void NewProjectDialog::on_lineEdit_textChanged(const QString &arg1)
{
    QString filePath = ui->lineEdit_2->text() +"/" + arg1 +".xml";
    ExistFile(filePath);
}

void NewProjectDialog::on_lineEdit_2_textChanged(const QString &arg1)
{
    QString filePath = arg1 +"/" + ui->lineEdit->text() +".xml";
    ExistFile(filePath);
}

